import { instructAttachmentPreview } from "../../../service/api/api-instruct-attachment";
import { receiptRecord, selectRecord } from "../../../service/api/api-instruct-record";

// pages/cues/topic/details/submitDetail/index.ts
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentUser: {},//当前用户
    access: {} as any,// 当前用户权限
    index: 0,//当前页在上一页中列表位置
    instructId: 0,//当前通知的id
    dataInstructDetails: {},//宣传部通知详情
    receiptVisible: false,//回执情况抽屉是否打开
    receiptList: [],//回执情况列表
    isSavereceiptNodes: [],//回显回执情况列表
    isLoadReceiptList: true,//是否正在加载回执情况列表
    previewData: {},//预览图片信息
    previewDataUrlType: 'preview',
    imageList: [],//现有的图片列表
    viewPreviewImageVisible: false,//是否预览图片
  },
  //预览图片
  async onClickPreviewImage(e) {
    const file = e.currentTarget.dataset.file
    const type = e.currentTarget.dataset.type
    if (!type.includes('image')) {
      const response = await instructAttachmentPreview({
        id: file.id,
      });
      if (response.code === 0) {
        this.setData({
          previewData: {
            title: file.name,
            onlinePreview: true,
            url: file.content,
            content: response.data,
          }
        })
        wx.navigateTo({
          url: '/pages/web/index?url=' + encodeURIComponent(this.data.previewData.content) + '&title=' + this.data.previewData.title + '&type=' + this.data.previewDataUrlType
        })
      } else {
        wx.showToast({
          title: '暂时无法预览',
          icon: 'error'
        })
      }
    } else {
      // const List = this.data.dataInstructDetails.attachments.filter((item: any) => item.mimeType.includes("image"));
      // const imageList = List.map((item) => item.content)
      const List = this.data.dataInstructDetails.attachments.filter((item: any) => {
        if (item.mimeType !== null) {
          return item.mimeType.includes("image")
        } else {
          return
        }
      });
      const imageList = List.map((item) => item.content)
      this.setData({
        imageList,
        viewPreviewImageVisible: true
      })
    }
  },
  //关闭图片预览
  onClosePreviewImage(e) {
    this.setData({
      viewPreviewImageVisible: false,
    });
  },
  //下载图片
  onDownloadFile(e) {
    const file = e.currentTarget.dataset.file
    wx.downloadFile({
      url: file.content,
      success: function (res) {
        // wx.showToast({
        //   title: '下载成功',
        //   icon: 'success',
        // })
        if (res.statusCode === 200) {
          const filePath = res.tempFilePath
          wx.openDocument({
            filePath: filePath,
            showMenu: true, //关键点
            success: function (res) {
              console.log('打开文档成功')
            }
          })
        }
      },
      fail: function (res) {
        wx.showToast({
          title: '下载失败',
          icon: 'error'
        })
      }
    })
  },
  /**
  * 加载 选题线索详情
  * @param key
  */
  async loadCuesTopicDetails(id) {
    try {
      const response = await selectRecord({ id });
      const { code, data } = response;
      if (code === 0) {
        this.setData({
          dataInstructDetails: data
        })
      }
    } catch (error) { }
  },
  /**
  * 预备Tree结构数据
  * @param data
  */
  readyTreeData(data: AdminOrganizationData.Organization[]): any {
    const treeData = [];
    if (data) {
      data.forEach((val) => {
        if (val.isFolder === 1 && val.children === undefined) {
        } else {
          treeData.push({
            name: val.name,
            id: val.id,
            parentId: val.parentId,
            checkbox: true,
            isFolder: val.isFolder,
            isChildren: val.children === undefined ? 0 : 1,
            children: this.readyTreeData(val.children as AdminOrganizationData.Organization[]),
          });
        }
      });
    }
    return treeData;
  },
  /**
* 处理已选中的数据
* @param data
*/
  readySelectData(data: AdminOrganizationData.Organization[]): any {
    const ids = [];
    function traverse(arr) {
      arr.forEach(item => {
        if (item.isView === 1) {
          ids.push(item.id);
        }
        if (item.children) {
          traverse(item.children);
        }
      });
    }
    traverse(data);
    return ids;
  },
  /**
* 预备Tree结构数据
* @param data
*/
  readyTreeData2(dataTree: [], selectIds: []): any {
    if (dataTree.length > 0) {
      let list = dataTree.map(item => {
        if (item.isChildren == 1) {
          item.children = this.readyTreeData2(item.children, selectIds);
          let noChildren = item.children.filter((item) => item.checked === 0); //过滤出未选中的
          let noLength = noChildren.length;
          if (noLength == 0) { //未选中的 == 0 ，选中状态
            let pingChildren = item.children.filter((item) => item.checked === -1); //过滤出平的，未全选中
            let pingLength = pingChildren.length;
            if (pingLength == 0) {//平的 == 0，选中状态
              item.checked = 1;
            } else {//平的 != 0, 平状态 
              item.checked = -1;
            }
          } else if (noLength == item.children.length) { //未选中的 == 孩子长度，表示 父节点 未选中
            item.checked = 0;
          } else { //未选中的 >0 && < 孩子长度，表示 父节点 平的
            item.checked = -1;
          }
          // console.log('================',item.name,'================',item.checked);
        } else {
          item.checked = selectIds.includes(item.id) ? 1 : 0
        }
        return item
      })
      return list;
    }
    return []
  },
  //加载回执情况列表
  async onLoadReceiptList(id) {
    const response = await receiptRecord({ id });
    if (response.code === 0) {
      this.setData({
        receiptList: this.readyTreeData(response.data),
        isLoadReceiptList: false
      })
      if (!this.data.isLoadReceiptList) {
        wx.hideLoading()
        this.setData({
          instructId: id,
          receiptVisible: true
        })
        this.setData({
          receiptList: this.readyTreeData2(this.data.receiptList, this.readySelectData(response.data))
        })

      }
    }
  },
  //打开查看回执情况抽屉
  onOpenReceipt() {
    this.onLoadReceiptList(this.data.instructId)
    this.setData({
      receiptVisible: true
    })
  },
  //关闭查看查看回执情况的抽屉
  closeReceipt() {
    this.setData({
      receiptVisible: false
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options: { instructId: any; mode: any; index: any; }) {
    this.setData({
      index: options.index
    })
    const { globalData: { access, currentUser } } = getApp();
    this.setData({
      access,
      currentUser,
      instructId: options.instructId,
    })
    this.loadCuesTopicDetails(options.instructId)
    //解决是否阅读标签实时更新问题
    let pages = getCurrentPages();// 获取页面栈
    let prevpage = pages[pages.length - 2]// 上一个页面
    if (prevpage) {//存在上一页
      let instructList = prevpage.data.instructList;
      instructList[options.index].isView = 1;
      prevpage.setData({ instructList })// 修改上一页的数据
    }
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {
    wx.setStorageSync('instruct-page', 'detail')
    wx.setStorageSync('instruct-detail-index', this.data.index)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})